/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.fxn.utils;

import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

/**
 * description : 关于操作Pixel的工具类
 *
 * @since 2021-04-12
 */
public class PixelUtil {
    private static Display display;

    /**
     * 初始化display, 建议此方法在BaseApplication里调用
     *
     * @param context context
     */
    public static void initContext(Context context) {
        display = DisplayManager.getInstance().getDefaultDisplay(context).get();
    }

    /**
     * 获取当前设备屏幕的宽
     *
     * @return 当前设备屏幕的宽
     */
    public static int screenWidth() {
        return display.getAttributes().width;
    }

    /**
     * 获取当前设备屏幕的高
     *
     * @return 当前设备屏幕的高
     */
    public static int screenHeight() {
        return display.getAttributes().height;
    }

    /**
     * fp转px的方法
     *
     * @param fp fp
     * @return 传入fp所对应的px值
     */
    public static float fp2px(float fp) {
        double sca = display.getAttributes().scalDensity;
        return (int) (fp * sca + 0.5F * (fp >= 0 ? 1 : -1));
    }

    /**
     * vp转px的方法
     *
     * @param vp vp
     * @return 传入vp所对应的px的值
     */
    public static float vp2px(int vp) {
        double dpi = display.getAttributes().densityPixels;
        return (int) (vp * dpi + 0.5F * (vp >= 0 ? 1 : -1));
    }
}
